if __name__=='__main__':
    import sys 
    import os 
    sys.path.append(os.path.abspath("."))   

import datetime
from flask import Blueprint, jsonify,request,url_for,redirect
from settings import FeeRate
from orm import Log,Room
import numpy as np 



# 计算费用
def Cost(res_time,speed,feerate):
    cost = 0.0
    if speed == 1:
        cost = (res_time / 10) / 3 * FeeRate
    elif speed == 2:
        cost = (res_time / 10) / 2 * FeeRate
    elif speed == 3:
        cost = (res_time / 10) * 1 * FeeRate
    return cost


def generate_detail_oder(id):
    re_data = []
    datafi = []
    # 读取数据
    for i,data in enumerate(Log.select().where((Log.slave_id==id)&(Log.res_time!=None))):
        re_data.append({'slave_id':data.slave_id,'speed':data.speed,'res_time':data.res_time})

    # 删除改变温度重复的log
    for k in range(len(re_data)):
        try:
            if re_data[k]['speed']==re_data[k+1]['speed']:
                re_data.pop(k+1)
        except:
            break        
    # 计算一次开关记得详单
    j=0
    while j<len(re_data):
        try:
            datafi.append({'房间号':re_data[j]['slave_id'],'服务开始时间':re_data[j]['res_time'],'服务结束时间':re_data[j+1]['res_time'],'服务时长':(re_data[j+1]['res_time']-re_data[j]['res_time']).seconds,'风速':re_data[j]['speed']})
            if re_data[j]['speed']!=0 and re_data[j+1]['speed']!=0:
                j+=1
                pass
            else:
                j+=2
        except:
            break

    # 加入计算的费用
    for num,log in enumerate(datafi):
        log['序号'] = num
        log['费率'] = FeeRate
        log['当前费用'] = Cost(log['服务时长'],log['风速'],FeeRate)

    subtotal = np.cumsum(np.array([part['当前费用'] for part in datafi]))
    # 加入请求时间和费用
    for num,q_time in enumerate(Log.select().where((Log.slave_id==id)&(Log.req_time!=None))):
        try:
            datafi[num]['请求时间'] = q_time.req_time 
            datafi[num]['小计'] = float(subtotal[num])
        except:
            break

    return datafi

def generate_bill(id):
    re_data={}
    detail = generate_detail_oder(id)
    room = Room.get(Room.id==id)
    re_data['房间号']= id
    re_data['入住时间'] = room.open_time
    re_data['退房时间'] = room.close_time
    re_data['空调总费用'] = detail[-1]['小计']
    return re_data

log = Blueprint('log', __name__)


@log.route('/detail/<id>')
def get_today_log(id):
    url = url_for('monitor.destroy',id=id)
    redirect(url,code=301)
    return jsonify(
        generate_detail_oder(id))


@log.route('/bill/<id>')
def get(id):
    return jsonify(
        generate_bill(id))